<?php defined('SYSPATH') or die('No direct script access.');
                          
class Payment_Controller extends Template_Controller 
{
	public $template = 'layout/order';
	
	public function __construct()
	{
		parent::__construct();
		
		$this->db = new Database();

		$this->template->menu = '';
		$this->template->content = '';
		$this->template->leftmenu = $this->db->query('SELECT * FROM product_categories WHERE left_id>1 AND right_id <(SELECT right_id FROM product_categories WHERE id=1) AND layer_id<=2 ORDER BY left_id');
	}
	
	public function index()
	{
	}
		
	public function success($order_id)
	{
		$order = new Order_Model($order_id);
		
		$config = config::item('email.options');
		
		$view = new View('order/customer_email');
		$view->order = $order;
		$view->items = $this->db->query('SELECT oi.*, p.title_cn, p.title_en, p.sku FROM order_items oi LEFT JOIN products p ON p.id=oi.product_id WHERE order_id='.$order_id);
		
		$from = $config['username'];   
		$subject = 'NanHai.com: order #'.$order->id.' ('.$order->updated_at.')';   
		$message = $view->render();   
			 
		if(email::send($order->email, $from, $subject, $message, true))
		{
			$order->flag_customer_email = 1;
		}
		
		if(email::send(config::item('bookstore.order_email'), $from, $subject, $message, true))
		{
			$order->flag_service_email = 1;
		} 
		
		$order->status = 1;
		$order->save();
		
		url::redirect('order/view/'.$order_id);
		exit;
	}
	
	public function cancel($order_id)
	{
		url::redirect('order/view/'.$order_id);
		exit;
	}
	
	public function notify()
	{
		$track = '';
		
		$req = 'cmd=_notify-validate';

		foreach ($_POST as $key => $value)
		{
			$value = urlencode(stripslashes($value));
			$req .= "&$key=$value";
		}
		
		// post back to PayPal system to validate
		$header  = "POST /cgi-bin/webscr HTTP/1.0\r\n";
		$header .= "Content-Type: application/x-www-form-urlencoded\r\n";
		$header .= "Content-Length: " . strlen($req) . "\r\n\r\n";
		$fp = fsockopen ('ssl://www.paypal.com', 443, $errno, $errstr, 30);
		
		if ($fp) 
		{
			fputs ($fp, $header . $req);
			
			while (!feof($fp)) 
			{
				$res = fgets ($fp, 1024);
				
				if (strcmp ($res, "VERIFIED") == 0) 
				{
					$track .= '<h3>VERIFIED</h3>';
					
					if( $_POST['payment_status'] == 'Completed' )
					{
						$order_id = str_replace('Order #', '', $_POST['item_name']);
						
						$order = new Order_Model($order_id);
						
						$order->status = 2;

						$config = config::item('email.options');
						
						$view = new View('order/customer_email');
						$view->order = $order;
						$view->items = $this->db->query('SELECT oi.*, p.title_cn, p.title_en, p.sku FROM order_items oi LEFT JOIN products p ON p.id=oi.product_id WHERE order_id='.$order_id);
						
						$from = $config['username'];   
						$subject = 'NanHai.com: order #'.$order->id.' ('.$order->updated_at.')';   
						$message = $view->render();   
							 
						if($order->flag_customer_email == 0)
						{
							if(email::send($order->email, $from, $subject, $message, true))
							{
								$order->flag_customer_email = 1;
								$track .= '<p>向'.$order->email.'发送邮件成功</p>';
							}
						}
						
						if($order->flag_service_email == 0)
						{
							if(email::send(config::item('bookstore.order_email'), $from, $subject, $message, true))
							{
								$order->flag_service_email = 1;
								$track .= '<p>向'.config::item('bookstore.order_email').'发送邮件成功</p>';
							} 
						}
						
						$order->status = 2;
						
						if($order->save())
						{
							$track .= '<p>['.$order->id.']号订单保存成功，订单状态['.$order->status.']</p>';
						}
					}
				}
				else if (strcmp ($res, "INVALID") == 0) 
				{
					$track .= '<h3>INVALID</h3>';
				}
			}
			fclose ($fp);
		}
		else
		{
			$track .= "<p>$errstr ($errno)</p>";
		}
			
		$track .= (isset($_POST['payment_status']) ? $_POST['payment_status'] : '').'<br/><br/>';
		
		foreach ($_POST as $key => $value)
		{
			$track .= "$key => $value<br/>";
		}
		
		$config = config::item('email.options');
		
		$from = $config['username'];   
		$subject = 'Nanhai.com: Paypal Notify';   
		email::send('hs0714@163.com', $from, $subject, $track, true);
		
		exit;
	}
	
	public function notify1()
	{
		$track = '';
		
		$req = 'cmd=_notify-validate';

		foreach ($_POST as $key => $value)
		{
			$value = urlencode(stripslashes($value));
			$req .= "&$key=$value";
		}
		
		// post back to PayPal system to validate
		$header  = "POST /cgi-bin/webscr HTTP/1.0\r\n";
		$header .= "Content-Type: application/x-www-form-urlencoded\r\n";
		$header .= "Content-Length: " . strlen($req) . "\r\n\r\n";
		$fp = fsockopen ('ssl://www.paypal.com', 443, $errno, $errstr, 30);
	
		if ($fp) 
		{
			fputs ($fp, $header . $req);
			
			while (!feof($fp)) 
			{
				$res = fgets ($fp, 1024);
				
				if (strcmp ($res, "VERIFIED") == 0) 
				{
					$track .= '<h3>VERIFIED</h3>';
					
					if( $_POST['payment_status'] == 'Completed' )
					{
						$order_id = str_replace('Order #', '', $_POST['item_name']);
						
						$order = new Order_Model($order_id);
						
						$order->status = 2;
						
						if($order->save())
						{
							$track .= '<p>['.$order_id.']号订单保存成功</p>';
						}
					}
				}
				else if (strcmp ($res, "INVALID") == 0) 
				{
					$track .= '<h3>INVALID</h3>';
				}
			}
			fclose ($fp);
		}
		else
		{
			$track .= "<p>$errstr ($errno)</p>";
		}
			
		$track .= (isset($_POST['payment_status']) ? $_POST['payment_status'] : '').'<br/><br/>';
		
		foreach ($_POST as $key => $value)
		{
			$track .= "$key => $value<br/>";
		}
		
		echo $track;
		
		exit;
	}
}